package com.sxkf.core.third.verify;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.green20220302.Client;
import com.aliyun.green20220302.models.*;
import com.aliyun.teaopenapi.models.Config;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


public class ContextCheckUtil {

    private static final String ACCESS_KEY_ID = "LTAI5tGTJE1hmpB986yZdqG2";
    private static final String ACCESS_KEY_SECRET = "zG1sjPvSOg716vPcDTL2iweLy3grIG";
    private static final Client client;

    static {
        try {
            client = new Client(getConfig());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Boolean checkText(String content){
        TextModerationPlusResponseBody.TextModerationPlusResponseBodyData textModerationPlusResponseBodyData = textModerationPlus(content);
        if (null != textModerationPlusResponseBodyData){
            for (TextModerationPlusResponseBody.TextModerationPlusResponseBodyDataResult dataResult : textModerationPlusResponseBodyData.getResult()) {
                if (dataResult.getLabel().equals("nonLabel")){
                    return true;
                }
                if (dataResult.getConfidence()>90){
                    return false;
                }
            }
        }
        return true;
    }

    public static VoiceModerationResultResponseBody.VoiceModerationResultResponseBodyData getVoiceResult(String taskId) {
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("taskId", taskId);
        VoiceModerationResultRequest voiceModerationResultRequest = new VoiceModerationResultRequest();
        voiceModerationResultRequest.setService("audio_media_detection");
        voiceModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VoiceModerationResultResponse response = client.voiceModerationResult(voiceModerationResultRequest);
            if (response.getStatusCode() == 200) {
                VoiceModerationResultResponseBody result = response.getBody();
                System.out.println("requestId=" + result.getRequestId());
                System.out.println("code=" + result.getCode());
                System.out.println("msg=" + result.getMessage());
                if (200 == result.getCode()) {
                    VoiceModerationResultResponseBody.VoiceModerationResultResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                    return data;
                } else {
                    System.out.println("voice moderation result not success. code:" + result.getCode());
                }
            } else {
                System.out.println("response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }

    public static VideoModerationResultResponseBody.VideoModerationResultResponseBodyData getVideoResult(String taskId) {
        JSONObject serviceParameters = new JSONObject();
        // 提交任务时返回的taskId。
        serviceParameters.put("taskId", taskId);

        VideoModerationResultRequest videoModerationResultRequest = new VideoModerationResultRequest();
        // 检测类型：videoDetection
        videoModerationResultRequest.setService("videoDetection");
        videoModerationResultRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResultResponse response = client.videoModerationResult(videoModerationResultRequest);
            if (response.getStatusCode() == 200) {
                VideoModerationResultResponseBody result = response.getBody();
                System.out.println("requestId=" + result.getRequestId());
                System.out.println("code=" + result.getCode());
                System.out.println("msg=" + result.getMessage());
                if (200 == result.getCode()) {
                    VideoModerationResultResponseBody.VideoModerationResultResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                    return data;
                } else {
                    System.out.println("video moderation result not success. code:" + result.getCode());
                }
            } else {
                System.out.println("response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }

    public static DescribeImageModerationResultResponseBody.DescribeImageModerationResultResponseBodyData getImageResult(String reqId) {
        DescribeImageModerationResultRequest imageModerationResultRequest = new DescribeImageModerationResultRequest();
        imageModerationResultRequest.setReqId(reqId);
        try {
            DescribeImageModerationResultResponse response = client.describeImageModerationResult(imageModerationResultRequest);
            if (response.getStatusCode() == 200) {
                DescribeImageModerationResultResponseBody result = response.getBody();
                System.out.println("requestId=" + result.getRequestId());
                System.out.println("code=" + result.getCode());
                System.out.println("msg=" + result.getMsg());
                if (200 == result.getCode()) {
                    DescribeImageModerationResultResponseBody.DescribeImageModerationResultResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                    return data;
                } else {
                    System.out.println("video moderation result not success. code:" + result.getCode());
                }
            } else {
                System.out.println("response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }

    public static String checkVoice(String audio) {

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("url", audio);

        VoiceModerationRequest voiceModerationRequest = new VoiceModerationRequest();
        voiceModerationRequest.setService("audio_media_detection");
        voiceModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VoiceModerationResponse response = client.voiceModeration(voiceModerationRequest);
            if (response.getStatusCode() == 200) {
                VoiceModerationResponseBody result = response.getBody();
                System.out.println(JSON.toJSONString(result));
                System.out.println("requestId = " + result.getRequestId());
                System.out.println("code = " + result.getCode());
                System.out.println("msg = " + result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    VoiceModerationResponseBody.VoiceModerationResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                    return data.getTaskId();
                } else {
                    System.out.println("voice moderation not success. code:" + code);
                }
            } else {
                System.out.println("response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }

    public static String checkVideo(String video) {
        VideoModerationRequest videoModerationRequest = new VideoModerationRequest();
        videoModerationRequest.setService("videoDetection");

        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("url", video);
        videoModerationRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            VideoModerationResponse response = client.videoModeration(videoModerationRequest);
            if (response.getStatusCode() == 200) {
                VideoModerationResponseBody result = response.getBody();
                System.out.println(JSON.toJSONString(result));
                System.out.println("requestId = " + result.getRequestId());
                System.out.println("code = " + result.getCode());
                System.out.println("msg = " + result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    VideoModerationResponseBody.VideoModerationResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                    return data.getTaskId();
                } else {
                    System.out.println("video moderation not success. code:" + code);
                }
            } else {
                System.out.println("response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }


    public static String checkImg(String img) {
        // 检测参数构造。
        Map<String, String> serviceParameters = new HashMap<>();
        //公网可访问的URL。
        serviceParameters.put("imageUrl", img);
        //待检测数据唯一标识
        serviceParameters.put("dataId", UUID.randomUUID().toString());

        ImageAsyncModerationRequest request = new ImageAsyncModerationRequest();
        request.setService("baselineCheck");
        request.setServiceParameters(JSON.toJSONString(serviceParameters));

        try {
            ImageAsyncModerationResponse response = client.imageAsyncModeration(request);
            if (response.getStatusCode() == 200) {
                ImageAsyncModerationResponseBody body = response.getBody();
                System.out.println("requestId=" + body.getRequestId());
                System.out.println("code=" + body.getCode());
                System.out.println("msg=" + body.getMsg());
                if (body.getCode() == 200) {
                    ImageAsyncModerationResponseBody.ImageAsyncModerationResponseBodyData data = body.getData();
                    System.out.println(JSON.toJSONString(data, true));
                    return data.getReqId();
                } else {
                    System.out.println("image moderation not success. code:" + body.getCode());
                }
            } else {
                System.out.println("response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }

    /**
     * 文字审核
     */
    public static TextModerationPlusResponseBody.TextModerationPlusResponseBodyData textModerationPlus(String content) {
        JSONObject serviceParameters = new JSONObject();
        serviceParameters.put("content", content);

        TextModerationPlusRequest textModerationPlusRequest = new TextModerationPlusRequest();
        // 检测类型
        textModerationPlusRequest.setService("llm_query_moderation");
        textModerationPlusRequest.setServiceParameters(serviceParameters.toJSONString());

        try {
            TextModerationPlusResponse response = client.textModerationPlus(textModerationPlusRequest);
            if (response.getStatusCode() == 200) {
                TextModerationPlusResponseBody result = response.getBody();
                System.out.println(JSON.toJSONString(result));
                System.out.println("requestId = " + result.getRequestId());
                System.out.println("code = " + result.getCode());
                System.out.println("msg = " + result.getMessage());
                Integer code = result.getCode();
                if (200 == code) {
                    TextModerationPlusResponseBody.TextModerationPlusResponseBodyData data = result.getData();
                    System.out.println(JSON.toJSONString(data, true));
                    return data;
                } else {
                    System.out.println("text moderation not success. code:" + code);
                }
            } else {
                System.out.println("response not success. status:" + response.getStatusCode());
            }
        } catch (Exception e) {
            e.fillInStackTrace();
        }
        return null;
    }

    @NotNull
    private static Config getConfig() {
        Config config = new Config();
        config.setAccessKeyId(ACCESS_KEY_ID);
        config.setAccessKeySecret(ACCESS_KEY_SECRET);
        //接入区域和地址请根据实际情况修改
        config.setRegionId("cn-shanghai");
        config.setEndpoint("green-cip.cn-shanghai.aliyuncs.com");
        //连接时超时时间，单位毫秒（ms）。
        config.setReadTimeout(6000);
        //读取时超时时间，单位毫秒（ms）。
        config.setConnectTimeout(3000);
        return config;
    }
}